<template>
  <div class="container" v-loading="loading" element-loading-text="数据处理中，请耐心等待......" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)">
    <el-row type="flex" justify="space-between">
      <div style="display:inline-flex;flex:1;align-items: center">
        <el-button @click="exportExcel" type="success" icon="el-icon-download">导出</el-button>
      </div>
      <div>
        <div style="margin-bottom: 10px;display:flex; justify-content: flex-end;align-items: center">
          <span style="font-size: 14px;margin-left:1%;width: 8%;">台网码:</span>
          <el-select multiple collapse-tags v-model="selectNetCode" placeholder="请选择台网码" style="width: 25%;" @change='changeSelectNetCode'>
            <el-checkbox  style="margin-left: 20px" v-model="checkedNetCode" @change='selectAllNetCode'>全选</el-checkbox>
            <el-option v-for="item in netCodeOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
          <el-date-picker style="margin-left:5%;width: 66%;" v-model="date"
                          type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"  value-format="yyyy-MM-dd">
          </el-date-picker>

        </div>
        <div style="display:flex; justify-content: flex-end;align-items: center">
          <span style="font-size: 14px;margin-left: 1%;width: 8%;">台站类型:</span>
          <el-select multiple collapse-tags v-model="selectStaType" placeholder="请选择台站类型" style="width: 25%;" @change='changeSelectStaType'>
            <el-checkbox  style="margin-left: 20px" v-model="checkedStaType" @change='selectAllStaType'>全选</el-checkbox>
            <el-option v-for="item in staTypeOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>

          <span style="font-size: 14px;margin-left: 3%;width: 8%">连续天数: </span>
          <el-input-number v-model="daysThreshold" :min="1" style="width: 25%" class="input-with-select" controls-position="right" >
          </el-input-number>
          <span style="font-size: 14px;margin-left: 2%;width: 8%;">下线天数:</span>
          <el-input placeholder="下线天数" type="number" min="0" v-model="errorTimesSumThreshold" style="width: 25%;" class="input-with-select">
            <el-select v-model="errorTimesSumLessThanSymbol" slot="prepend" placeholder="阈值" style="width: 110px">
              <el-option label="大于等于" value="大于等于"></el-option>
              <el-option label="小于等于" value="小于等于"></el-option>
            </el-select>
          </el-input>
        </div>
      </div>
      <div style="display:flex; justify-content: flex-end;flex:2;align-items: center" >
        <el-button style="margin-left: 10px" @click="queryData" type="primary" icon="el-icon-search">查询</el-button>
        <el-button style="margin-left: 10px" @click="clearFn" type="danger" icon="el-icon-delete">清除</el-button>
      </div>
    </el-row>
    <el-table :data="tableData" style="width: 100%;margin-top:15px;" border :cell-style="cellStyle" :row-style="{height:'40px'}" >
      <el-table-column prop="netCode" label="台网名称" align="center" fixed>
      </el-table-column>
      <el-table-column prop="staCode" label="台站名称" align="center">
      </el-table-column>
      <el-table-column prop="staType" label="台站类型" align="center">
      </el-table-column>
      <el-table-column :label="item" align="center" show-overflow-tooltip v-for="(item, index) in tableTitle" :key="index">
        <template slot-scope="scope">
          {{scope.row.dataList[index].isOffline}}
        </template>
      </el-table-column>
      <el-table-column prop="errorTimesSum" label="下线天数" align="center" show-overflow-tooltip fixed="right">
      </el-table-column>
    </el-table>
    <div class="page">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageInfo.pageNum" :page-sizes="[5, 10, 15, 20]" :page-size="pageInfo.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

  </div>
</template>

<script>
import { getOfflineData, getAllNetCode, getNetCode, getAllStaType } from '@/api'
export default {
  name: 'Home',
  data () {
    return {
      tableData: [],
      tableTitle: [],
      pageInfo: {
        endDate: '',
        pageNum: 1,
        pageSize: 10,
        startDate: ''
      },
      netCode: [], // 台网码数组,用于sheet命名
      netCodeOptions: [],
      selectChanCode: '',
      selectChanNum: '',
      staTypeOptions: [],
      selectNetCode: '',
      selectStaType: '',
      date: '',
      total: 0,
      loading: false,
      daysThreshold: 3, // 阈值
      errorTimesSumThreshold: 4,
      errorTimesSumLessThanSymbol: '大于等于',
      continuousErrorTimesThreshold: 1,
      checkedNetCode: true,
      checkedStaType: true

    }
  },
  created () {
    this.$notify.info({
      title: '提示',
      message: '请选择筛选项'
    })
    const dateRange = this.getDefaultDate()
    this.pageInfo.startDate = dateRange[0]
    this.pageInfo.endDate = dateRange[1]
    this.date = [dateRange[0], dateRange[1]]
    this.getBaseData()
    // this.getList()
    this.getNetCode()
  },
  methods: {
    selectAllNetCode () {
      this.selectNetCode = []
      if (this.checkedNetCode) {
        this.netCodeOptions.forEach((item) => { this.selectNetCode.push(item.value) })
      } else {
        this.selectNetCode = []
      }
      console.log(this.selectNetCode)
    },
    changeSelectNetCode (val) {
      if (val.length === this.netCodeOptions.length) {
        this.checkedNetCode = true
      } else {
        this.checkedNetCode = false
      }
      console.log(this.selectNetCode)
    },
    selectAllStaType () {
      this.selectStaType = []
      if (this.checkedStaType) {
        this.staTypeOptions.forEach((item) => { this.selectStaType.push(item.value) })
      } else {
        this.selectStaType = []
      }
      console.log(this.selectStaType)
    },
    changeSelectStaType (val) {
      if (val.length === this.staTypeOptions.length) {
        this.checkedStaType = true
      } else {
        this.checkedStaType = false
      }
      console.log(this.selectStaType)
    },
    getDefaultDate () {
      const date = new Date()// 当前时间
      const year = date.getFullYear() // 返回指定日期的年份
      const month = this.repairDate(date.getMonth() + 1)// 月
      const day = this.repairDate(date.getDate())// 日

      // 当前时间
      const endDate = year + '-' + month + '-' + day

      const date2 = new Date(date)
      date2.setDate(date2.getDate() - 6)
      const year2 = date2.getFullYear() // 返回指定日期的年份
      const month2 = this.repairDate(date2.getMonth() + 1)// 月
      const day2 = this.repairDate(date2.getDate())// 日
      const startDate = year2 + '-' + month2 + '-' + day2
      const dateRange = [startDate, endDate]

      return dateRange
    },
    repairDate (i) {
      if (i >= 0 && i <= 9) {
        return '0' + i
      } else {
        return i
      }
    },
    async getBaseData () {
      const { data: { data: data1 } } = await getAllNetCode()
      this.netCodeOptions = data1.map(item => ({ value: item, label: item }))
      this.selectAllNetCode()
      const { data: { data: data2 } } = await getAllStaType()
      this.staTypeOptions = data2.map(item => ({ value: item, label: item }))
      this.selectAllStaType()
    },
    async getList () {
      if (!this.date || this.selectNetCode.length === 0 || this.selectStaType.length === 0 || !this.daysThreshold ||
        this.daysThreshold === '' || this.errorTimesSumThreshold === '' ||
        this.daysThreshold === null || this.errorTimesSumThreshold === null) {
        this.$notify.info({
          title: '提示',
          message: '请检查所有筛选项不能为空'
        })
      } else {
        this.loading = true
        if (!this.date) {
          const dateRange = this.getDefaultDate()
          this.date = [dateRange[0], dateRange[1]]
        }
        // 数据组装
        this.queryInfo = {
          ...this.pageInfo,
          netCodeList: this.selectNetCode,
          daysThreshold: this.daysThreshold,
          staTypeList: this.selectStaType,
          errorTimesSumThreshold: this.errorTimesSumThreshold,
          errorTimesSumLessThanSymbol: this.errorTimesSumLessThanSymbol === '小于等于',
          continuousErrorTimesThreshold: this.continuousErrorTimesThreshold,
          chanCodeList: [],
          chanNumList: []
        }

        const { data: { data } } = await getOfflineData(this.queryInfo)
        this.tableData = data.records
        if (data.records.length !== 0) {
          const list = data.records[0].dataList
          if (list.length !== 0) {
            this.tableTitle = list.map(item => item.date)
          }
        }
        this.total = data.total

        if (data.records.length === 0) {
          this.$notify.info({
            title: '提示',
            message: '设定时间段内无错误/异常数据'
          })
        }
        this.loading = false
      }
    },
    handleSizeChange (newSize) {
      this.pageInfo.pageSize = newSize
      this.getList()
    },
    handleCurrentChange (newNum) {
      this.pageInfo.pageNum = newNum
      this.getList()
    },
    queryData () {
      if (this.date) {
        this.pageInfo.startDate = this.date[0]
        this.pageInfo.endDate = this.date[1]
      }
      this.pageInfo.pageNum = 1
      this.pageInfo.pageSize = 10
      this.getList()
    },
    clearFn () {
      const dateRange = this.getDefaultDate()
      this.date = [dateRange[0], dateRange[1]]
      this.pageInfo = {
        endDate: dateRange[1],
        pageNum: 1,
        pageSize: 10,
        startDate: dateRange[0]
      }
      this.selectNetCode = []
      this.daysThreshold = 1
      this.selectStaType = []
      this.errorTimesSumThreshold = 0
      this.errorTimesSumLessThanSymbol = '大于等于'
      this.continuousErrorTimesThreshold = 1

      this.getList()
    },
    async getNetCode () {
      const { data: { data } } = await getNetCode()
      this.netCode = data
    },
    cellStyle ({ row, column, rowIndex, columnIndex }) {
      if (column.label !== '台网名称' && column.label !== '台站名称' && column.label !== '台站类型' && column.label !== '下线天数') {
        if (row.dataList[columnIndex - 3].continuousState) {
          return 'background:#ffeb9c;color:black;padding:0px'
        } else {
          return 'background:#00FF7F;color:black;padding:0px'
        }
      }
      return 'padding:0px'
    },
    async exportExcel () {
      if (!this.date || this.selectNetCode.length === 0 || this.selectStaType.length === 0 || !this.daysThreshold ||
        this.daysThreshold === '' || this.errorTimesSumThreshold === '' ||
        this.daysThreshold === null || this.errorTimesSumThreshold === null) {
        this.$notify.info({
          title: '提示',
          message: '请检查所有筛选项不能为空'
        })
      } else {
        if (!this.date) return this.$message.error('请指定导出范围~')
        this.$notify.info({
          title: '提示',
          message: '开始下载下线站点情况统计.xlsx文件，请稍候'
        })
        // 包裹多表数据变量定义
        const allHeader = []
        const allMerges = []
        const allData = []
        const allSheetName = []
        const dic = new Map()
        const allColorCol = []// sheet1全为空，sheet是每一行对应的需要变的颜色

        // 解决forEach异步问题
        const promiseArray = []
        const queryInfo = {
          endDate: this.date[1],
          startDate: this.date[0],
          pageNum: 1,
          pageSize: -1,
          netCodeList: this.selectNetCode,
          daysThreshold: this.daysThreshold,
          staTypeList: this.selectStaType,
          errorTimesSumThreshold: this.errorTimesSumThreshold,
          errorTimesSumLessThanSymbol: this.errorTimesSumLessThanSymbol === '小于等于',
          continuousErrorTimesThreshold: this.continuousErrorTimesThreshold,
          chanCodeList: [],
          chanNumList: []

        }
        const header = ['台网名称', '台站名称', '台站类型', ...this.tableTitle, '下线天数'] // 标题

        const netCodes = this.selectNetCode
        netCodes.push('') // 加入总表
        // 获取数据,有多个台网的，这里先做一个的测试
        netCodes.forEach(async netCode => {
          if (netCode !== '') {
            queryInfo.netCodeList = [netCode]
          } else {
            queryInfo.netCodeList = this.selectNetCode
          }
          const s = new Promise((resolve, reject) => {
            const sheet = {
              header: header,
              data: [],
              colorCol: []
            }
            getOfflineData(queryInfo).then(({ data: { data } }) => {
            // 数据组装,data数组有多长，说明就有几天的，也就是说有几行的数据
              const colLength = this.tableTitle.length

              for (let i = 0; i < colLength; i++) {
                sheet.colorCol.push([])
              }

              data.records.forEach(item => {
                var row = []
                const obj1 = JSON.parse(JSON.stringify(item, ['netCode',
                  'staCode', 'staType'], 4))
                const obj2 = item.dataList.map(date => date.isOffline === null ? '' : date.isOffline)

                const obj = []
                for (var a in obj1) {
                  obj.push(obj1[a])
                }
                for (let i = 0; i < colLength; i++) {
                  if (item.dataList[i].continuousState) {
                    sheet.colorCol[i].push('黄色')
                  } else {
                    sheet.colorCol[i].push('')
                  }
                }
                row = [...obj, ...obj2, item.errorTimesSum]
                sheet.data.push(row)
              })
              allMerges.push([])
              dic.set(netCode, sheet)
              // 代表本次执行完
              resolve()
            })
          })
          promiseArray.push(s)
        })

        Promise.all(promiseArray).then(() => {
          netCodes.forEach(async netCode => {
            const sheetName = netCode
            const sheet = dic.get(sheetName)
            allHeader.push(sheet.header)
            allData.push(sheet.data)
            allSheetName.push(sheetName === '' ? '总表' : sheetName) // 加入总表
            allColorCol.push(sheet.colorCol)
          })

          import('@/utils/exportAllDate').then(excel => {
            excel.export_json_to_excel({
            // header: [header],
              header: allHeader,
              // data: [[['鹿琛', '12']], [['尘世', '18']]],
              // data: [tableData],
              data: allData,
              filename: '下线站点情况统计',
              autoWidth: true,
              // merges: [[]],
              merges: allMerges,
              SheetNames: allSheetName,
              bookType: 'xlsx',
              colorCol: this.tableTitle,
              colorColData: allColorCol
            })
          })
        })
      }
    },
    async exportDefaultExcel () {
      if (!this.daysThreshold) {
        this.daysThreshold = 1
      }
      if (!this.doubleFilteredThreshold) {
        this.doubleFilteredThreshold = 0
      }
      if (!this.errorTimesSumThreshold) {
        this.errorTimesSumThreshold = 0
      }
      this.loading = true

      // 包裹多表数据变量定义
      const allHeader = []
      const allMerges = []
      const allData = []
      const allSheetName = []
      const dic = new Map()
      const allColorCol = []// sheet1全为空，sheet是每一行对应的需要变的颜色

      const dateRange = this.getDefaultDate()

      // 解决forEach异步问题
      const promiseArray = []

      await this.getNetCode()
      await this.getBaseData()

      const allNetCode = []
      const allStaType = []
      this.netCodeOptions.map((item) => {
        allNetCode.push(item.value)
      })
      this.staTypeOptions.map((item) => {
        allStaType.push(item.value)
      })
      const queryInfo = {
        endDate: dateRange[1],
        startDate: dateRange[0],
        pageNum: 1,
        pageSize: -1,
        netCodeList: [],
        daysThreshold: 1,
        staTypeList: allStaType,
        errorTimesSumThreshold: 0,
        errorTimesSumLessThanSymbol: false,
        continuousErrorTimesThreshold: 0,
        chanCodeList: [],
        chanNumList: []
      }

      let netCodes = []
      netCodes = this.netCode
      netCodes.push('') // 加入总表
      let tableTitle = []

      // 获取数据,有多个台网的，这里先做一个的测试
      netCodes.forEach(async netCode => {
        if (netCode !== '') {
          queryInfo.netCodeList = [netCode]
        } else {
          queryInfo.netCodeList = this.selectNetCode
        }
        const s = new Promise((resolve, reject) => {
          const sheet = {
            header: [],
            data: [],
            colorCol: []
          }
          getOfflineData(queryInfo).then(({ data: { data } }) => {
            // 数据组装,data数组有多长，说明就有几天的，也就是说有几行的数据
            if (data.records.length !== 0) {
              const list = data.records[0].dataList
              if (list.length !== 0) {
                tableTitle = list.map(item => item.date)
              }
            }

            const header = ['台网名称', '台站名称', '台站类型', ...tableTitle, '下线天数'] // 标题
            sheet.header = header
            const colLength = tableTitle.length

            for (let i = 0; i < colLength; i++) {
              sheet.colorCol.push([])
            }

            data.records.forEach(item => {
              var row = []
              const obj1 = JSON.parse(JSON.stringify(item, ['netCode',
                'staCode', 'staType'], 4))
              const obj2 = item.dataList.map(date => date.isOffline === null ? '' : date.isOffline)
              const obj = []
              for (var a in obj1) {
                obj.push(obj1[a])
              }
              for (let i = 0; i < colLength; i++) {
                if (item.dataList[i].continuousState) {
                  sheet.colorCol[i].push('红色')
                } else {
                  sheet.colorCol[i].push('')
                }
              }
              row = [...obj, ...obj2, item.errorTimesSum]
              sheet.data.push(row)
            })
            allMerges.push([])
            dic.set(netCode, sheet)
            // 代表本次执行完
            resolve()
          })
        })
        promiseArray.push(s)
      })

      const date = new Date()// 当前时间
      const year = date.getFullYear() // 返回指定日期的年份
      const month = (date.getMonth() + 1 + '').padStart(2, '0')// 月
      const day = (date.getDate() + '').padStart(2, '0')// 日
      const hour = (date.getHours() + '').padStart(2, '0')
      const fileName = year + '-' + month + '-' + day + ' ' + hour + '时_下线站点情况统计'

      Promise.all(promiseArray).then(() => {
        netCodes.forEach(async netCode => {
          const sheetName = netCode
          const sheet = dic.get(sheetName)
          allHeader.push(sheet.header)
          allData.push(sheet.data)
          allSheetName.push(sheetName === '' ? '总表' : sheetName) // 加入总表
          allColorCol.push(sheet.colorCol)
        })

        import('@/utils/exportAllDate').then(excel => {
          excel.export_json_to_excel({
            // header: [header],
            header: allHeader,
            // data: [[['鹿琛', '12']], [['尘世', '18']]],
            // data: [tableData],
            data: allData,
            filename: fileName,
            autoWidth: true,
            // merges: [[]],
            merges: allMerges,
            SheetNames: allSheetName,
            bookType: 'xlsx',
            colorCol: this.tableTitle,
            colorColData: allColorCol
          })
        })
      })
    }

  }

}
</script>
<style lang="less" scoped>
.page {
  margin-top: 20px;
}
.container {
  // padding-top: 20px;
  height: calc(100vh - 60px);
}

</style>
